﻿using Nancy;
using Nancy.ModelBinding;
using Nancy.Swagger;
using Nancy.Swagger.Annotations.Attributes;
using NancyTest.Models;
using NancyTest.Utility.Extension;
using Swagger.ObjectModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace NancyTest
{
    public class HomeModule : NancyModule
    {

        public HomeModule(ISwaggerModelCatalog modelCatalog)
        {
            //涉及到哪些Model
            modelCatalog.AddModel<RetData>();
            modelCatalog.AddModel<UploadData>();

            //路由
            Get("/getData", dynamic => Index(), null, "GetData");
            Get("/queryData", dynamic =>
            {
                string userName = Request.Query.userName ?? "";
                return QueryData(userName);
            }, null, "QueryData");
            Post("/postForm", dynamic => UploadData(dynamic.Id, dynamic.Name), null, "PostForm");
            Post("/uploadFile", dynamic =>
            {
                IEnumerable<HttpFile> files = Request.Files;
                if (files == null || files.Count() == 0)
                    return UploadFile(null);
                return UploadFile(files.FirstOrDefault());
            }, null, "UploadFile");
            //这个就不需要Swagger显示了，不需要注解
            Get("/upload/{name*}", dynamic => ShowUploadFile(dynamic.name ?? ""), null, "GetUploadFile");
            Post("/postJson", dynamic =>
            {
                UploadData config = this.Bind<UploadData>();
                return UploadJson(config);
            }, null, "PostJson");
        }

        private object ShowUploadFile(string name)
        {
            string contentType = MimeTypes.GetMimeType(name);
            return Response.AsFile(MyEnvironment.Root("/Upload/" + name), contentType);
        }

        [Route("GetData")]//Name
        [Route(HttpMethod.Get, "/getData")]//Method And Path
        [Route(Summary = "获得XX数据")]
        [SwaggerResponse(HttpStatusCode.OK, typeof(RetData))]
        [Route(Tags = new[] { "获得XX数据Tag" })]
        private object Index()
        {
            return Response.AsJson(new RetData { state = 1, message = "Hello World!" });
        }

        [Route("QueryData")]//Name
        [Route(HttpMethod.Get, "/queryData")]//Method And Path
        [Route(Summary = "获得某用户的数据")]
        [SwaggerResponse(HttpStatusCode.OK, typeof(RetData))]
        [Route(Tags = new[] { "获得某用户的数据Tag" })]
        private object QueryData([RouteParam(ParameterIn.Query, Name = "userName", Description = "用户名")] string userName)
        {
            return new RetData { state = 1, message = "查询成功", data = "用户XX,年龄18" };
        }




        [Route("PostForm")]//Name
        [Route(HttpMethod.Post, "/postForm")]//Method And Path
        [Route(Summary = "上传XX数据")]
        [SwaggerResponse(HttpStatusCode.OK, typeof(RetData))]
        [Route(Tags = new[] { "上传XX数据Tag" })]
        private object UploadData([RouteParam(ParameterIn.Form, Name = "id", Description = "ID")] string id, [RouteParam(ParameterIn.Form, Name = "name", Description = "姓名")] string name)
        {
            return Response.AsJson(new RetData { state = 1, message = "上传成功" });
        }


        [Route("UploadFile")]//Name
        [Route(HttpMethod.Post, "/uploadFile")]//Method And Path
        [Route(Summary = "文件上传")]
        [SwaggerResponse(HttpStatusCode.OK, typeof(RetData))]
        [Route(Tags = new[] { "文件上传Tag" })]
        private object UploadFile([RouteParam(ParamIn = ParameterIn.Form, Name = "file", Description = "文件", ParamType = typeof(SwaggerFile), Required = true)] HttpFile file)
        {
            //保存文件
            string uploadPath = MyEnvironment.Root("/Upload/");
            if (!Directory.Exists(uploadPath))
            {
                Directory.CreateDirectory(uploadPath);
            }
            string ext = Path.GetExtension(file.Name);
            string fileName = Guid.NewGuid().ToString().Replace("-", "") + ext;
            //完整路径
            var filePath = uploadPath + fileName;
            using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
            {
                file.Value.CopyTo(fileStream);
            }
            var virtualPath = "/Upload/" + fileName;
            //返回虚拟路径
            return Response.AsJson(new RetData { state = 1, message = "上传成功", data = virtualPath });
        }




        [Route("PostJson")]//Name
        [Route(HttpMethod.Post, "/postJson")]//Method And Path
        [Route(Summary = "上传XXX数据")]
        [SwaggerResponse(HttpStatusCode.OK, typeof(RetData))]
        [Route(Tags = new[] { "上传XXX数据Tag" })]
        private object UploadJson([RouteParam(ParameterIn.Body, Name = "data", Description = "JSON数据上传")] UploadData config)
        {
            return Response.AsJson(new RetData { state = 1, message = "上传成功" });
        }
    }
}
